import * as Localization from "expo-localization";
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import { storage } from "@/utils/storage";

import translationEn from "./locales/en-US/translation.json";
import translationZh from "./locales/zh-CN/translation.json";

const resources = {
  zh: { translation: translationZh },
  en: { translation: translationEn },
};

i18n
  .use(initReactI18next)
  .use({
    type: "languageDetector",
    async: true,
    detect: async (callback: (arg0: string) => void) => {
      let locale;
      locale = await storage.getItem("language");
      if (!locale) {
        const locales = Localization.getLocales();
        locale = locales[0]?.languageTag || "zh"; // 使用第一个语言环境
      }
      callback(locale);
    },
    cacheUserLanguage: (language: string) => {
      storage.setItem("language", language);
    },
  })
  .init({
    resources,
    fallbackLng: "zh",
    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;
